<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>
        <div id="title">
            <!-- 给每个按钮绑定自定义属性用来点击获取属性 -->
            <button data-url="/news">新闻</button>
            <button data-url="/music">音乐</button>
            <button data-url="/games">游戏</button>
        </div>
        <div id="view"></div>
    </div>

    <script>
        const oBtns = document.querySelectorAll("#title button");
        const oView = document.getElementById("view");

        //1.创建路由表
        const routers = [
            { path: "/news", context: "海阔天空" },
            { path: "/music", context: "see you again" },
            { path: "/games", context: "必杀技" },
        ]

        //遍历所有的btns 绑定点击事件
        for (var i = 0; i < oBtns.length; i++) {
            oBtns[i].onclick = function () {
                //2.点击拿到按钮上保存的url 然后改变地址栏的hash值
                location.hash = this.dataset.url
            };
        }

        //监听地址栏hash值的改变 更新视图
        window.onhashchange = function (e) {
            //拿到新的hash地址
            const newHash = e.newURL.split("#")[1]

            //遍历路由表更新视图
            routers.forEach((item) => {
                if(item.path === newHash){
                    //如果地址栏中的hash值和路由表中的相等 则把这一项对应的context添加到视图
                    oView.textContent = item.context;
                }
            })
        }
    </script>
</body>

</html>